<?php

namespace control;
/*
*查看凭证类
*/

class voucherClass extends adIndexClass
{
    private const page = 'voucher';
    private const table = 'voucher';
    private const tableMx = 'voucher_detail';
    private const title = '查看凭证';
    private const listOption = ['100' => '按凭证号重新顺次排序', '200' => '按凭证日期重新顺次编号'];

    public static function joinWhere(): string
    {
        $setting = optionSettingClass::getSetting('总账');
        if (!$setting['afterAuditMark']) {
            return " and workFlow !='已作废'";
        } else {
            return " and a.workFlow ='已记账'";
        }
    }

    public static function auditWhere(): string
    {
        $settingInfo = query('option_setting', "type = '总账' and coid = '" . self::$coid . "'");
        $setting = json_decode($settingInfo['setting'], true);
        if (!$setting['afterAuditMark']) {
            return " and workFlow !='已作废'";
        } else {
            return " and workFlow ='已记账'";
        }
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(array("name" => "createTime", 'laydate' => ['type' => 'month', 'range' => '~'])),
                    "凭证字"   => idSelect(array('name' => 'voucherWordId', 'sqlForm' => "voucher_word where coid = '" . self::$coid . "'", 'sqlId' => 'id', 'sqlField' => 'word')),
                    "凭证号"=>text(array("name" => "vNoFrom",'class'=>'width100')).'-'.text(array("name" => "vNoTo",'class'=>'width100')),
                ],
                [
                    "金额"=>text(array("name" => "mFrom",'class'=>'width100')).'-'.text(array("name" => "mTo",'class'=>'width100')),
                    '摘要'  => text(array("name" => "summary")),
                    "科目" => componentClass::customSubject(['name' => 'formSubjectId','title' => '请选择']) ,
                ],
                [
                    "签字" => radio(['name'=>'signState','value'=>['是','否','不限'],'checked'=>'不限']),
                    "审核" => radio(['name'=>'auditState','value'=>['是','否','不限'],'checked'=>'不限']),
                    "凭证作废" => radio(['name'=>'cancelState','value'=>['是','否','不限'],'checked'=>'不限']),
                ],
                [
                    "外币凭证" => radio(['name'=>'isCurrency','value'=>['是','否','不限'],'checked'=>'不限']),
                    "数量核算" => radio(['name'=>'isNumCheck','value'=>['是','否','不限'],'checked'=>'不限']),
                ],
                [
                    '制单人' => selectMultiple(["name" => "stid", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    "备注" => text(array("name" => "text")),
                ],
                [
                    '排序依据' => radio(['name'=>'sort','value'=>['凭证字号','日期'],'checked'=>'凭证字号']),
                    "排序方式" => radio(['name'=>'sortWay','value'=>['升序','降序'],'checked'=>'升序']),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = $this->buttonList('全部', 'listForm');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {

        $json['html'] = $this->content('listForm', '全部');
        return json_encode($json, 320);
    }

    public function content($formName, $workFlow, $where = ''): string
    {
        //like查询数组
        $like = array(
            "text" => $this->post('text'),//备注
        );
        //全等查询数组
        $equal = array(
            'workFlow' => $this->post('workFlow'),
            'voucherWordId' => $this->post('voucherWordId'),
            'stid' => $this->post('stid'),
            'coid' => self::$coid,
            'isTemplate' => '否'
        );
        $and = '';
        if ($this->post('cancelState')){
            $and .=match ($this->post('cancelState')){
                '是' => " and workFlow = '已作废'",
                '否' => " and workFlow != '已作废'",
                '不限' => ''
            };
        }
        if ($this->post('signState')){
            $and .=match ($this->post('signState')){
                '是' => " and workFlow = '已签字'",
                '否' => " and workFlow != '已签字'",
                '不限' => ''
            };
        }
        if ($this->post('auditState')){
            $and .=match ($this->post('auditState')){
                '是' => " and workFlow = '已审核'",
                '否' => " and workFlow != '已审核'",
                '不限' => ''
            };
        }
        if ($this->post('mFrom')){
            $and .=" and (money/100) >='".$this->post('mFrom')."'";
        }
        if ($this->post('mTo')){
            $and .=" and (money/100) <='".$this->post('mTo')."'";
        }
        if ($this->post('vNoFrom')){
            $and .=" and voucherNo >='".$this->post('vNoFrom')."'";
        }
        if ($this->post('vNoTo')){
            $and .=" and voucherNo <='".$this->post('vNoTo')."'";
        }
        if ($this->post('createTime')) {

        }
        $timeSlot = $this->post('createTime') ?: date('Y-m').'~'.date('Y-m');
        $and .= self::timeComparison($timeSlot, 'month', 'recordDate');

        $mAnd = '';
        if ($this->post('summary')) {
            $mAnd .= " and summary like '%" . $this->post('summary') . "%'";
        }
        if ($this->post('isCurrency')) {
            $mAnd .=match ($this->post('isCurrency')){
                '是' => " and currencyId !=''",
                '否' => " and currencyId =''",
                '不限' => ''
            };
        }
        if ($this->post('isNumCheck')) {
            $mAnd .=match ($this->post('isNumCheck')){
                '是' => " and voucherNum > 0",
                '否' => " and voucherNum = 0",
                '不限' => ''
            };
        }
        if ($this->post('formSubjectId')) {
            $subjectObj = new subjectClass();
            $subjectIdArr = $subjectObj->getFromToSubject($this->post('formSubjectId'), $this->post('toSubjectId'));
            $mAnd.=" and subjectId in ('" . implode("','", $subjectIdArr) . "')";
        }
        if ($mAnd){
            $and .= " and id in (select distinct orderId from " . self::tableMx . " where coid = '" . self::$coid . "' $mAnd)";
        }
        $sortWay = '';
        if ($this->post('sortWay')) {
            $sortWay.=match ($this->post('sortWay')){
                '升序' => " ASC",
                '降序' => " DESC",
            };
        }
        $orderBy = '';
        if ($this->post('sort')) {
            $orderBy.=match ($this->post('sort')){
                '凭证字号' => "voucherNo $sortWay",
                '日期' => "date_format(recordDate,'%Y-%m') $sortWay,voucherNo $sortWay",
            };
        }

        //获取查询结果
        $where .= search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy));
        static::rSet(self::$stid . self::page . 'Sql', $page['fullSql']);

        //获取最新结账日期
        $checkout = query('checkout', "coid = '" . self::$coid . "' order by month desc");
        $assetObj = new assetDebtClass();
        $url = root . "control/adIndex.html?cla=voucherEdit&fun=home";
        // 月份选择器
        $monthSelector = componentClass::monthSelector($timeSlot);
        //获取表头
        //获取记录
        $html = <<<eof
<div class="voucher-body">
    <div class='voucher-title'>
        <div class='td-title' style="width: 50px;padding-left: 5px">
        <span><input class="checked_box" type="checkbox" form="{$formName}" name="listId" onchange="checkAll(this)">&nbsp;</span></div>
        <div class='td-title' style='width: 324px'></span>摘要</div>
        <div class='td-title'>科目</div>
        <div class='td-title' style='width: 104px;text-align: right'>借方金额</div>
        <div class='td-title' style='width: 104px;text-align: right'>贷方金额</div>
        <div style="text-align: right;padding-right: 10px"><div style='display: inline-flex;gap: 5px'>操作{$monthSelector['button']}</div></div>
    </div>
    <div class="voucher-list">
eof;
        $cancelPower = $this->power(self::page,'cancel');
        foreach ($page['array'] as $array) {
            $editName = '编辑';
            if (date('Y-m', strtotime($array['recordDate'])) <= $checkout['month'] || $array['workFlow'] != '待审核') {
                //此凭证在结账期间内，则不可更改
                $editName = '查看';
            }
            $delButton = <<<eof
<span class="del-row-button right mlf" onclick="layer('voucher','operate',{act:'del',id:'{$array['id']}'})">删除</span>
eof;
            $auditButton = '';
            if ($array['workFlow'] != '待审核') {
                $delButton = '';
                $auditButton = <<<eof
<span class="del-row-button right mlf" onclick="layer('voucher','back',{id:'{$array['id']}'})">反审</span>
eof;
            }
            $stateSign = $this->stateSign($array['workFlow']);

            $voucherWord = query('voucher_word', "id = '$array[voucherWordId]'");

            $voucherNo = componentClass::urlTitle($voucherWord['word'] . '-' . $array['voucherNo'], root . 'control/adIndex.html?cla=voucherEdit&fun=room&id=' . $array['id'], '新增凭证');

            $fileNum = static::total(array('table' => 'file', 'where' => "targetId = '$array[id]' and target = '财务凭证'"));

            $fileBtn = $fileNum > 0 ? "<span style='margin-left: 30px' class='del-row-button' onclick=\"layer('component','fileDetail',{id:'" . $array['id'] . "'})\">附件：{$fileNum}</span>" : '';
            $receiptNum = $array['receiptNum']>0?"<span style='margin-left: 30px'>附单据{$array['receiptNum']}张</span>":'';
            $cancelButton='';//作废/取消作废
            if ($cancelPower){
                $cancelButton = "<span class='del-row-button right mlf' onclick=\"layer('voucher','cancelV',{id:'{$array['id']}'})\">作废</span>";
                if ($array['workFlow'] =='已作废'){
                    $cancelButton = "<span class='del-row-button right mlf' onclick=\"layer('voucher','cancelV',{id:'{$array['id']}'})\">取消作废</span>";
                }
            }

            $html .= <<<eof
<div class="voucher-list-item" data-id="$array[id]">
    $stateSign
    <div class="voucher-list-head">
        <span><input class="checked_box" type="checkbox"  name="listId[]" value="$array[id]">&nbsp;</span>
        <span style="margin-left: 29px">日期：{$array['recordDate']} </span>
        <span style="margin-left: 30px">凭证字号：$voucherNo</span>
        $receiptNum
        $fileBtn
        $auditButton
        <span class="del-row-button right mlf" onclick="window.open(root+'control/adIndex.html?cla=voucherEdit&fun=printPage&id={$array['id']}')">打印</span>
        $cancelButton
        <span class="del-row-button right mlf" onclick="newIframe('新增凭证','{$url}&method=redChong&id={$array['id']}')">红冲</span>
        <span class="del-row-button right mlf" onclick="newIframe('新增凭证','{$url}&method=insert&id={$array['id']}')">插入</span>
        $delButton
        <span class="del-row-button right mlf" onclick="newIframe('新增凭证','{$url}&id={$array['id']}')">$editName</span>
        <span class="del-row-button right mlf" onclick="newIframe('新增凭证','{$url}&method=template&id={$array['id']}')">复制</span>
        
    </div>
    <div class="voucher-list-lines">

eof;

            $all = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]' order by rowList,list asc"));

            $jieTotal = $daiTotal = 0;
            foreach ($all['array'] as $val) {
                $jieMoney = $val['direction'] == '借' ? self::centToYuan($val['money']) : 0;
                $daiMoney = $val['direction'] == '贷' ? self::centToYuan($val['money']) : 0;
                $jieTotal += $jieMoney;
                $daiTotal += $daiMoney;
                $jieMoney = $assetObj->fontColor($jieMoney);
                $daiMoney = $assetObj->fontColor($daiMoney);
                $html .= <<<eof
<div class="voucher-list-line">
    <div style="width: 50px"></div>
    <div style="width: 314px">{$val['summary']}</div>
    <div>{$this->assitName($val)}</div>
    <div class="line-jie-col" style="width: 104px;text-align: right">{$jieMoney}</div>
    <div class="line-dai-col" style="width: 104px;text-align: right">{$daiMoney}</div>
</div>
eof;
            }
            $daxie = ($jieTotal < 0 ? '负' : '') . voucherEditClass::num_to_rmb(abs($jieTotal));
            $jieTotal = $assetObj->fontColor($jieTotal);
            $daiTotal = $assetObj->fontColor($daiTotal);


            $html .= <<<eof
        <div class="voucher-list-line voucher-list-total">
            <div style="width: 50px"></div>
            <div style="width: 314px">合计：$daxie</div>
            <div></div>
            <div class="line-jie-col" style="width: 105px;text-align: right">$jieTotal</div>
            <div class="line-dai-col" style="width: 107px;text-align: right">$daiTotal</div>
        </div>
    </div>
</div>
eof;

        }
        if (is_array($page['array']) && count($page['array']) == 0) {
            $html .= <<<eof
<div class="voucher-list-item">
一条数据也没有
</div>
eof;
        }
        $html .= <<<eof
</div>
</div>
eof;

        $html .= $this->style() . $this->js();

        $button = "";
        //返回
        return $page['hint'] .
            $button .
            "<div class='acct-main-container'>
                <form name='{$formName}'>" .
                    $html .
                "</form>".
                $monthSelector['html'].
            "</div>" .
            clear .
            $page['button'] .
            clear;
    }

    /**
     * 状态标志
     * @param $workFlow
     * @return string
     */
    public function stateSign($workFlow): string
    {
        switch ($workFlow) {
            case '待审核':
                $class='blue-sign';
                break;
            case '待签字':
                $class='green-sign';
                break;
            case '待记账':
                $class='orange-sign';
                break;
            case '已记账':
                $class = 'gray-sign';
                break;
            case '已作废':
                $class = 'red-sign';
                break;
            default:
                $class='';
                break;
        }
        return <<<eof
<div class="out-cycle $class">
    <div class="inner-cycle $class">
    {$workFlow}
</div>
</div>
eof;
    }

    /**
     * 反审
     * @return bool|string
     */
    public function back(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否确认反审此凭证？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "提示", "height" => 165, "html" => $html));
    }


    public function backEdit(): bool|string
    {
        $id = $this->post('id');
        $voucher = query(self::table, "id = '$id'");
        //获取最新结账日期
        $checkout = query('checkout', "coid = '" . self::$coid . "' order by month desc");
        if (empty($id)) {
            $json['warn'] = '未找到ID';
        } elseif (!$this->power(self::page, 'audit') && !$this->power(self::page, 'sign') && !$this->power(self::page, 'record')) {
            $json['warn'] = '您还没有' . self::title . '的反审的权限';
        } elseif ($voucher['workFlow'] == '待审核') {
            $json['warn'] = "反审失败:凭证还未审核";
        }elseif (date('Y-m', strtotime($voucher['recordDate'])) <= $checkout['month']) {
            //返回
            $json['warn'] = "反审失败：已结账不可反审";
        } else {
            $warn = update(array('table' => self::table, 'field' => ['workFlow' => '待审核', 'auditStid' => '', 'auditTime' => '', 'signStid' => '', 'signTime' => '', 'recordStid' => '', 'recordTime' => ''], 'where' => "id = '$id'"));
            if ($warn == '更新成功') {
                $voucherWord = query('voucher_word', "id = '$voucher[voucherWordId]'");
                auditClass::operateRecord($id, '凭证', '反审');
                $text = $this->control['name'] . "反审了凭证【{$voucher['id']}】,【{$voucherWord['word']}-{$voucher['voucherNo']}】,日期【{$voucher['recordDate']}】";
                $this->logText(["type" => self::page, "text" => $text]);
                $json['warn'] = 2;
                $_SESSION['warn'] = "反审成功";
            } else {
                $json['warn'] = '反审失败';
            }
        }
        return json_encode($json, 320);
    }

    public function cancelV(){
        $info = query(self::table,"id = '".$this->post('id')."'");
        $title = "是否确认作废？";
        if ($info['workFlow'] =='已作废'){
            $title = "是否确认取消作废？";
        }
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => $title,
            ),
        )));
        //返回
        return $this->layer(array("title" => "提示", "height" => 165,"width" => 600, "html" => $html));
    }

    public function cancelVEdit(): bool|string
    {
        $id = $this->post('id');
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '您还没有' . self::title . '的作废权限';
        }elseif(empty($id)){
            $json['warn'] = '未找到需要操作的数据';
        } else {
            $info = query(self::table, "id = '$id'");
            $voucher = query('voucher_word', "id = '" . $info['voucherWordId'] . "'");
            if ($info['workFlow'] == '已作废') {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => [
                        'workFlow'=>'待审核'
                    ],
                    "where" => "id = '$id'"
                ]);
                $text = $this->control['name'] ."取消作废凭证【{$voucher['word']}-{$info['voucherNo']}】,日期【{$info['recordDate']}】";
                $warn = '取消作废凭证成功';
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => [
                        'workFlow'=>'已作废'
                    ],
                    "where" => "id = '$id'"
                ]);
                $text = $this->control['name'] ."作废了凭证【{$voucher['word']}-{$info['voucherNo']}】,日期【{$info['recordDate']}】";
                $warn = '作废凭证成功';
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $warn;
                $json['warn'] = 2;
            }
        }
        resp:
        return json_encode($json, 320);
    }


    /**
     * 审核
     * @return bool|string
     */
    public function auditVoucher(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否确认审核？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "提示", "height" => 165, "html" => $html, 'formTwo' => $this->post('formName')));
    }

    public function auditVoucherEdit(): bool|string
    {
        $listId = $this->post('listId');
        if (static::is_null_array($listId)) {
            $json['warn'] = '请选择数据';
        } elseif (!$this->power(self::page, 'audit')) {
            $json['warn'] = '您还没有' . self::title . '的审核权限';
        } else {
            $x = 0;
            $text = '';
            $setting = optionSettingClass::getSetting('总账');

            foreach ($listId as $id) {
                $voucher = query(self::table, "id = '$id'");
                $voucherWord = query('voucher_word', "id = '$voucher[voucherWordId]'");
                if ($voucher['workFlow'] != '待审核') {
                    $text .= "凭证【{$voucher['id']}】,【{$voucherWord['word']}-{$voucher['voucherNo']}】审核失败:不是待审核状态<br>";
                } elseif (!$setting['sameAudit'] && $voucher['stid'] == self::$stid) {
                    $text .= "凭证【{$voucher['id']}】,【{$voucherWord['word']}-{$voucher['voucherNo']}】审核失败:制单人和审核人不能相同，若需相同人员审核，请前往选项设置修改<br>";
                } else {
//                    $voucherChild = find(array('table' => self::tableMx, 'where' => "orderId = '$id'"));
                    $workFlow = '已记账';
//                    foreach ($voucherChild['array'] as $array) {
//                        $subject = query('subject', "id = '$array[subjectId]'");
//                        if ($setting['cashierSign'] && $subject['subjectSign'] == '现金流') {
//                            $workFlow = '待签字';
//                            break;
//                        }
//                    }
                    $warn = update(array('table' => self::table, 'field' => ['workFlow' => $workFlow, 'auditStid' => self::$stid, 'auditTime' => $this->time], 'where' => "id = '$id'"));
                    if ($warn == '更新成功') {
                        if (!$setting['afterAuditMark'] && $setting['dayBook']) {
                            //凭证生效后生成日记账
                            $this->bookAccount($voucher['id']);
                        }
                        $x++;
                        $text .= "凭证【{$voucher['id']}】,【{$voucherWord['word']}-{$voucher['voucherNo']}】，日期【{$voucher['recordDate']}】审核成功<br>";
                        auditClass::operateRecord($id, '凭证', '审核');
                    } else {
                        $text .= "凭证【{$voucher['id']}】,【{$voucherWord['word']}-{$voucher['voucherNo']}】，日期【{$voucher['recordDate']}】审核失败<br>";
                    }
                }

            }
            $text = $this->control['name'] . '审核了凭证如下：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
            $_SESSION['warn'] = "成功审核了{$x}条数据";
        }
        return json_encode($json, 320);
    }


    /**
     * 签字
     * @return bool|string
     */
    public function signVoucher(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否确认签字？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "提示", "height" => 165, "html" => $html, 'formTwo' => $this->post('formName')));
    }

    public function signVoucherEdit(): bool|string
    {
        $listId = $this->post('listId');
        if (static::is_null_array($listId)) {
            $json['warn'] = '请选择数据';
        } elseif (!$this->power(self::page, 'sign')) {
            $json['warn'] = '您还没有' . self::title . '的签字权限';
        } else {
            $x = 0;
            $text = '';
            $setting = optionSettingClass::getSetting('总账');
            foreach ($listId as $id) {
                $voucher = query(self::table, "id = '$id'");
                $voucherWord = query('voucher_word', "id = '$voucher[voucherWordId]'");
                if ($voucher['workFlow'] != '待签字') {
                    $text .= "凭证【{$voucher['id']}】,【{$voucherWord['word']}-{$voucher['voucherNo']}签字失败:不是待签字状态<br>";
                } else {
                    $warn = update(array('table' => self::table, 'field' => ['workFlow' => '待记账', 'signStid' => self::$stid, 'signTime' => $this->time], 'where' => "id = '$id'"));
                    if ($warn == '更新成功') {
                        if (!$setting['afterAuditMark'] && $setting['dayBook']) {
                            //凭证生效后生成日记账
                            $this->bookAccount($voucher['id']);
                        }
                        $x++;
                        $text .= "凭证【{$voucher['id']}】,【{$voucherWord['word']}-{$voucher['voucherNo']}】签字成功<br>";
                        auditClass::operateRecord($id, '凭证', '签字');
                    } else {
                        $text .= "凭证【{$voucher['id']}】,【{$voucherWord['word']}-{$voucher['voucherNo']}】签字失败<br>";
                    }
                }
            }
            $text = $this->control['name'] . '给凭证签字如下：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
            $_SESSION['warn'] = "成功签字了{$x}个凭证";
        }
        return json_encode($json, 320);
    }

    /**
     * 生成日记账
     */
    public function bookAccount($id)
    {
        $voucher = query(self::table, "id = '$id'");
        $voucherAll = find(array('table' => self::tableMx, 'where' => "orderId = '$id' order by list"));
        $account = [];
        foreach ($voucherAll['array'] as $array) {
            $account = query('account', "coid = '" . self::$coid . "' and subjectId = '$array[subjectId]'");
            if ($account['id']) {
                break;
            }
        }
        if (isset($account['id']) && $account['id']) {
            foreach ($voucherAll['array'] as $array) {
                if ($array['subjectId'] == $account['subjectId']) {
                    continue;
                }
                $type = $account['type'] == '银行存款' ? '银行账户' : '现金';
                //根据凭证模板查询对应科目
                $template = query('bookkeeping_setting', "type = '$type' and coid = '" . self::$coid . "' and subjectId = '$array[subjectId]'");
                if ($template['id']) {
                    $companyName = '';
                    if ($array['khid']) {
                        $companyName = query('kehu', "khid = '$array[khid]")['companyName'];
                    } elseif ($array['supplierId']) {
                        $companyName = query('supplierId', "id = '$array[khid]")['name'];
                    }
                    $income = $expenses = 0;
                    if ($array['direction'] == '借') {
                        $income = self::centToYuan($array['money']);
                    } else {
                        $expenses = self::centToYuan($array['money']);
                    }
                    $field = [
                        'id' => $id,
                        'type' => $type,
                        'coid' => self::$coid,
                        'stid' => self::$stid,
                        'accountId' => $account['id'],
                        'classify' => $template['classify'],
                        'recordDate' => $voucher['recordDate'],
                        'company' => $companyName,
                        'summary' => $array['summary'],
                        'income' => $income,
                        'expenses' => $expenses,
                        'settleType' => '',
                        'billNo' => '',
                        'text' => '',
                        'voucherId' => '',
                    ];
                    $userNo = codeTemplateClass::generateCode(self::page, [
                        'prefix' => date('Ymd'),
                        'table' => self::table,
                        'field' => 'orderNo',
                        'where' => " and coid = '" . self::$coid . "'",
                    ], $field);
                    $field['orderNo'] = $userNo;
                    insert(array('table' => 'bookkeeping', 'field' => $field));
                } else {
                    $this->logText(["type" => self::page, "text" => $this->control['name'] . "签字凭证【{$voucher['id']}】，明细【{$array['id']}】自动生成日记账失败：未找到日记账凭证配置"]);
                }
            }
        } else {
            $this->logText(["type" => self::page, "text" => $this->control['name'] . "签字凭证【{$voucher['id']}】自动生成日记账失败：未找到对应账户"]);
        }
    }

    /**
     * 记账
     * @return bool|string
     */
    public function recordVoucher(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否确认记账？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "提示", "height" => 165, "html" => $html, 'formTwo' => $this->post('formName')));
    }

    public function recordVoucherEdit(): bool|string
    {
        $listId = $this->post('listId');
        if (static::is_null_array($listId)) {
            $json['warn'] = '请选择数据';
        } elseif (!$this->power(self::page, 'record')) {
            $json['warn'] = '您还没有' . self::title . '的记账权限';
        } else {
            $x = 0;
            $text = '';
            foreach ($listId as $id) {
                $voucher = query(self::table, "id = '$id'");
                $voucherWord = query('voucher_word', "id = '$voucher[voucherWordId]'");
                if ($voucher['workFlow'] != '待记账') {
                    $text .= "凭证【{$voucher['id']}】,【{$voucherWord['word']}-{$voucher['voucherNo']}记账失败:不是待记账状态<br>";
                } else {
                    $warn = update(array('table' => self::table, 'field' => ['workFlow' => '已记账', 'recordStid' => self::$stid, 'recordTime' => $this->time], 'where' => "id = '$id'"));
                    if ($warn == '更新成功') {
                        $x++;
                        $text .= "凭证【{$voucher['id']}】,【{$voucherWord['word']}-{$voucher['voucherNo']}】记账成功<br>";
                        auditClass::operateRecord($id, '凭证', '记账');
                    } else {
                        $text .= "凭证【{$voucher['id']}】,【{$voucherWord['word']}-{$voucher['voucherNo']}】记账失败<br>";
                    }
                }

            }
            $text = $this->control['name'] . '给凭证记账如下：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
            $_SESSION['warn'] = "成功记账了{$x}个凭证";
        }
        return json_encode($json, 320);
    }

    public function buttonList($workFlow, $formName): string
    {
        //控件
        $button = "";
        switch ($workFlow) {
            case '待审核':

                if ($this->power(self::page, "print")) {
                    $button .= "<span onclick=\"printMultiple('{$formName}')\" class='spanButton'>打印</span>\n ";
                }
                if ($this->power(self::page, "audit")) {
                    $button .= "<span onclick=\"layer('" . self::page . "','auditVoucher',{formName:'{$formName}'})\" class='spanButton'>批量审核</span>\n ";
                }
                break;
            case '待签字':

                if ($this->power(self::page, "print")) {
                    $button .= "<span onclick=\"printMultiple('{$formName}')\" class='spanButton'>打印</span>\n ";
                }
//                if ($this->power(self::page, "sign")) {
//                    $button .= "<span onclick=\"layer('" . self::page . "','signVoucher',{formName:'{$formName}'})\" class='spanButton'>批量签字</span>\n ";
//                }
                break;
            case '待记账':

                if ($this->power(self::page, "print")) {
                    $button .= "<span onclick=\"printMultiple('{$formName}')\" class='spanButton'>打印</span>\n ";
                }
//                if ($this->power(self::page, "record")) {
//                    $button .= "<span onclick=\"layer('" . self::page . "','recordVoucher',{formName:'{$formName}'})\" class='spanButton'>批量记账</span>\n ";
//                }
                break;
            default:
                if ($this->power(self::page, "edit")) {
                    $button .= "<span onclick=\"layer('" . self::page . "','tidy',{})\" class='spanButton'>整理凭证</span>\n ";
                }
                if ($this->power(self::page, "audit")) {
                    $button .= "<span onclick=\"layer('" . self::page . "','auditVoucher',{formName:'{$formName}'})\" class='spanButton'>批量审核</span>\n ";
                }
//                if ($this->power(self::page, "sign")) {
//                    $button .= "<span onclick=\"layer('" . self::page . "','signVoucher',{formName:'{$formName}'})\" class='spanButton'>批量签字</span>\n ";
//                }
//                if ($this->power(self::page, "record")) {
//                    $button .= "<span onclick=\"layer('" . self::page . "','recordVoucher',{formName:'{$formName}'})\" class='spanButton'>批量记账</span>\n ";
//                }
                if ($this->power(self::page, 'import')) {
                    $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
                }
                if ($this->power(self::page, "export")) {
                    $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
                }
                if ($this->power(self::page, "print")) {
                    $button .= "<span onclick=\"printMultiple('{$formName}')\" class='spanButton'>打印</span>\n ";
                }
                if ($this->power(self::page, "del")) {
                    $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
                }
                break;
        }

        return $button;
    }



    /**
     * 科目名称
     * @param $array
     * @param bool $isWithSubject
     * @return string
     */
    public function assitName($array, $isWithSubject = true): string
    {
        $assetName = $isWithSubject ? ($array['subjectCode'] . ' ' . subjectClass::getName($array['subjectId'])) : '';
        if ($array['khid']) {
            $kehu = query('kehu', "khid = '$array[khid]'");
            $assetName .= '_' . $kehu['companyName'];
        }
        if ($array['supplierId']) {
            $supplier = query('supplier', "id = '$array[supplierId]'");
            $assetName .= '_' . $supplier['name'];
        }
        if ($array['staffId']) {
            $staff = query('staff', "stid = '$array[staffId]'");
            $assetName .= '_' . $staff['name'];
        }
        if ($array['projectId']) {
            $project = query('project', "id = '$array[projectId]'");
            $assetName .= '_' . $project['name'];
        }
        if ($array['materialId']) {
            $assetName .= '_' . materialClass::getName($array['materialId'], '');
        }
        if ($array['cashId']) {
            $cash = query('cash', "id = '$array[cashId]'");
            $assetName .= '_' . $cash['name'];
        }
        if ($array['departmentId']) {
            $department = query('department', "id = '$array[departmentId]'");
            $assetName .= '_' . $department['name'];
        }
        return ltrim($assetName, '_');
    }


    private function js()
    {
        return <<<eof
<script>
$(".voucher-list-item").on('dblclick',function() {
    newIframe('新增凭证',root+'control/adIndex.html?cla=voucherEdit&fun=room&id='+$(this).data('id'))
})
function printMultiple(formName){
    let arr = [];
    $("[name='"+formName+"'] input[type=checkbox]:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    let vals = arr.join(",");
    if (!vals){
        msg('请选择需要打印的数据','error');
        return false;
    }
    window.open(root+'control/adIndex.html?cla=voucherEdit&fun=printPage&listId='+vals)
    
}
</script>
eof;

    }

    /**
     * 整理凭证
     */
    public function tidy()
    {
        //表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "整理期间：" => text(array('name' => 'month', 'laydate' => ['type' => 'month'], 'value' => date('Y-m'))),
            ),
            array(
                "凭证字：" => idSelect(array('name' => 'voucherWordId', 'sqlForm' => "voucher_word where coid = '" . self::$coid . "' order by time", 'sqlId' => 'id', 'sqlField' => 'title', 'title' => '全部')),
            ),
            array(
                "类型：" => radio(array('name' => 'type', 'value' => self::listOption, 'checked' => '100')),
            ),
        )));
        //返回
        return $this->layer(array("title" => "整理凭证", "height" => 300, 'width' => 600, "html" => $html));
    }

    public function tidyEdit()
    {
        $month = $this->post('month');
        $voucherWordId = $this->post('voucherWordId');
        $type = $this->post('type');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($month)) {
            $json['warn'] = '请选择整理期间';
        } else {
            $where = '';
            if ($voucherWordId) {
                $where .= " and voucherWordId = '$voucherWordId'";
            }
            if ($type == '100') {
                //凭证号排序
                $all = find(array('table' => 'voucher', 'where' => "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m')='$month' and isTemplate = '否' $where order by voucherWordId,voucherNo"));
            } else {
                //凭证日期排序
                $all = find(array('table' => 'voucher', 'where' => "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m')='$month' and isTemplate = '否' $where order by voucherWordId,recordDate,list"));
            }
            $listType = [];
            foreach ($all['array'] as $index => $array) {
                if (!isset($listType[$array['voucherWordId']])) {
//                    $voucherNo = $this->voucherNo($array['voucherWordId'], $type, $month);
                    $listType[$array['voucherWordId']] = 1;
                } else {
                    $listType[$array['voucherWordId']]++;
                }
                update(array('table' => 'voucher', 'field' => ['voucherNo' => $listType[$array['voucherWordId']]], 'where' => "id = '$array[id]'"));
            }
            $text = $this->control['name'] . "整理了凭证";
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
            $_SESSION['warn'] = '整理成功';
        }
        return json_encode($json, 320);
    }



    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by recordDate asc,voucherNo asc",
                ))['array'];
            }else{
                $sql = static::rGet(self::$stid . self::page . 'Sql');
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){

                $voucherWord = query('voucher_word', "id = '$array[voucherWordId]'");
                $childAll = find(array('table' => self::tableMx, "where" => "orderId = '$array[id]' order by rowList,list asc"));
                foreach ($childAll['array'] as $item) {
                    $column = [];
                    $item['money'] = self::centToYuan($item['money']);
                    $currency = query('currency', "id = '$item[currencyId]'");
                    $subjectAttr = json_decode($item['subjectAttr'], true);
                    if ($item['direction'] == '借') {
                        $jieMoney = $item['money'];
                        $daiMoney = 0;
                        $jieNum = voucherEditClass::formatZero($item['voucherNum']);
                        $daiNum = 0;
                    } else {
                        $jieMoney = 0;
                        $daiMoney = $item['money'];
                        $daiNum = voucherEditClass::formatZero($item['voucherNum']);
                        $jieNum = 0;
                    }
                    $kehu = query('kehu', "khid = '$item[khid]'");
                    $supplier = query('supplier', "id = '$item[supplierId]'");
                    $staff = query('staff', "stid = '$item[staffId]'");
                    $department = query('department', "id = '$item[departmentId]'");
                    $project = query('project', "id = '$item[projectId]'");
                    $material = query('material', "id = '$item[materialId]'");
                    $cash = query('cash', "id = '$item[cashId]'");
                    foreach ($tempFieldAll as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '日期'=>$array['recordDate'],
                                '凭证号'=>$voucherWord['word'] . '-' . $array['voucherNo'],
                                '摘要'=>$item['summary'],
                                '科目编码'=>$item['subjectCode'],
                                '科目名称'=> subjectClass::getName($item['subjectId']),
                                '外币代码'=> $currency['code'],
                                '借方数量'=> self::zeroToEmpty($jieNum),
                                '借方外币'=>self::zeroToEmpty($jieMoney * $subjectAttr['voucherRate']),
                                '借方本币'=>  self::zeroToEmpty($jieMoney),
                                '贷方数量'=> self::zeroToEmpty($daiNum),
                                '贷方外币'=>self::zeroToEmpty($daiMoney * $subjectAttr['voucherRate']),
                                '贷方本币'=> self::zeroToEmpty($daiMoney),
                                '计量单位'=> $item['unit'],
                                '客户编码'=> $kehu['orderNo'],
                                '客户名称'=> $kehu['companyName'],
                                '供应商编码'=> $supplier['code'],
                                '供应商名称'=> $supplier['name'],
                                '员工编码'=>  $staff['orderNo'],
                                '员工名称'=>  $staff['name'],
                                '部门编码'=> $department['orderNo'],
                                '部门名称'=> $department['name'],
                                '项目编码'=> $project['orderNo'],
                                '项目名称'=> $project['name'],
                                '存货编码'=>$material['barcode'],
                                '存货名称'=> materialClass::getName($item['materialId'], ''),
                                '现金流编码'=>$cash['code'],
                                '现金流名称'=>  $cash['name'],
                                '备注'=>$array['text'],
                                default=>'',
                            };
                        }
                    }
                    $data[] = $column;
                }
            }
            $text = $this->control['name'] . "导出了凭证";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "凭证表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        }  else {
            $exampleData[] = ['2022-01-01', '记-1', '提现', '1001', '库存现金', '', '', '', '100', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
            $exampleData[] = ['2022-01-01', '记-1', '提现', '1001', '银行存款', '', '', '', '', '', '', '100', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '日期'=>$example[0],
                            '凭证号'=>$example[1],
                            '摘要'=>$example[2],
                            '科目编码'=>$example[3],
                            '科目名称'=>$example[4],
                            '外币代码'=>$example[5],
                            '借方数量'=>$example[6],
                            '借方外币'=>$example[7],
                            '借方本币'=>$example[8],
                            '贷方数量'=>$example[9],
                            '贷方外币'=>$example[10],
                            '贷方本币'=>$example[11],
                            '客户编码'=>$example[12],
                            '客户名称'=>$example[13],
                            '供应商编码'=>$example[14],
                            '供应商名称'=>$example[15],
                            '员工编码'=>$example[16],
                            '员工名称'=>$example[17],
                            '部门编码'=>$example[18],
                            '部门名称'=>$example[19],
                            '项目编码'=>$example[20],
                            '项目名称'=>$example[21],
                            '存货编码'=>$example[22],
                            '存货名称'=>$example[23],
                            '现金流编码'=>$example[24],
                            '现金流名称'=>$example[25],
                            '备注'=>$example[26],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }

            $text = $this->control['name'] . "下载了凭证导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $company = query('company', "coid = '" . self::$coid . "'");
            $x = 0;
            $text = '';
            $preVoucher = '';
            $voucherNumAdd = para('voucherNumAdd');
            $voucherInfo = [];
            $jieTotal = $daiTotal = 0;
            $line = 0;
            $succeed = 0;//成功的条数
            $headArray = [];
            $row_list=0;
            $this->startTrans();
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $line++;
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $cell['借方本币'] = $cell['借方本币'] ?: 0;
                    $cell['贷方本币'] = $cell['贷方本币'] ?: 0;
                    $cell['借方数量'] = $cell['借方数量'] ?: 0;
                    $cell['贷方数量'] = $cell['贷方数量'] ?: 0;
                    //主表
                    $voucher = explode('-', $cell['凭证号']);
                    $voucherWord = query('voucher_word', "coid = '" . self::$coid . "' and word = '$voucher[0]'");
                    if (empty($preVoucher) || $preVoucher != $cell['凭证号']) {
                        $voucherInfo = [];
                        $field = [
                            'id' => suiji(),
                            'stid' => self::$stid,
                            'source' => '正常',
                            'coid' => self::$coid,
                            'recordDate' => self::importDateFormat($cell['日期']),
                            'voucherWordId' => $voucherWord['id'],
                            'voucherNo' => $voucher[1],
                            'text' => $cell['备注'],
                        ];

                        $annotation = [
                            'recordDate' => '日期',
                            'voucherWordId' => '凭证字',
                        ];
                        $rules = [
                            'recordDate' => 'required',
                            'voucherWordId' => 'required',
                        ];
                        $month = date('Y-m', strtotime($field['recordDate']));
                        // 校验是否符合规则
                        $vt = new \verify();
                        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                        if ($result === false) {
                            $text .= "第【{$row_list}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                        } elseif (empty($voucherWord['id'])) {
                            $text .= "第【{$row_list}】行：未找到凭证字<br>";
                        } elseif ($voucherNumAdd == '否' && (empty($field['voucherNo']) || preg_match(checkInteger, $field['voucherNo']) == 0)) {
                            $text .= "第【{$row_list}】行：未找到凭证号<br>";
                        } elseif ($voucherNumAdd == '否' && static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and date_format(recordDate,'%Y-%m') = '$month' and isTemplate = '否' and voucherWordId = '$field[voucherWordId]' and voucherNo='$field[voucherNo]'")) > 0) {
                            $text .= "第【{$row_list}】行：已存在此凭证字号<br>";
                        } elseif (date('Y-m', strtotime($field['recordDate'])) < $company['startDate']) {
                            $text .= "第【{$row_list}】行：日期小于账套启用日期<br>";
                        } else {
                            $jieTotal = $daiTotal = 0;
                            if ($voucherNumAdd == '是') {
                                //自动补号
                                $field['voucherNo'] = voucherEditClass::voucherNo($field['voucherWordId'], $field['recordDate']);
                            }
                            $warn = insert(["table" => self::table, "field" => $field]);
                            if (in_array($warn, ["新增成功", "更新成功"])) {
                                $voucherInfo = $field;
                                $text .= "第【{$row_list}】行：成功<br>";
                            } else {
                                $text .= "第【{$row_list}】行失败：编辑失败<br>";
                            }
                        }
                    }

                    if (isset($voucherInfo['id']) && !empty($voucherInfo['id'])) {
                        //明细
                        $subject = query('subject', "code = '$cell[科目编码]' and coid = '" . self::$coid . "'");
                        $currency = query('currency', "code = '$cell[外币代码]' and coid = '" . self::$coid . "'");
                        if (empty($subject['id'])) {
                            $text .= "第【{$row_list}】行：未找到科目<br>";
                        } elseif (!empty($cell['借方本币']) && !empty($cell['贷方本币'])) {
                            $text .= "第【{$row_list}】行：不能同时填写借方和贷方<br>";
                        } elseif (empty($cell['借方本币']) && empty($cell['贷方本币'])) {
                            $text .= "第【{$row_list}】行：借方和贷方请至少填写一个<br>";
                        } else {
                            $direction = '借';
                            if ($cell['贷方本币'] != 0) {
                                $direction = '贷';
                            }
                            $kehu = query('kehu', "coid = '" . self::$coid . "' and orderNo = '$cell[客户编码]'");
                            $supplier = query('supplier', "coid = '" . self::$coid . "' and code = '$cell[供应商编码]'");
                            $staff = query('staff', "orderNo = '$cell[员工编码]'");
                            $department = query('department', "orderNo = '$cell[部门编码]'");
                            $project = query('project', "coid = '" . self::$coid . "' and orderNo = '$cell[项目编码]'");
                            $cash = query('cash', "coid = '" . self::$coid . "' and code = '$cell[现金流编码]'");
                            $material = query('material', "coid = '" . self::$coid . "' and barcode = '$cell[存货编码]'");
                            if (empty($material['id'])) {
                                $material = query('material', "coid = '" . self::$coid . "' and code = '$cell[存货编码]'");
                            }
                            $money = $direction == '借' ? self::yuanToCent($cell['借方本币']) : self::yuanToCent($cell['贷方本币']);
                            if ($direction == '借') {
                                $jieTotal += $money;
                            } else {
                                $daiTotal += $money;
                            }
                            $voucherRate = $cell['借方外币'] ? round($cell['借方本币'] / $cell['借方外币'], 4) : 0;
                            $voucherPrice = $cell['借方数量'] ? voucherEditClass::formatPrice($money / $cell['借方数量']) : 0;
                            $collection = [
                                'voucherPrice' => $voucherPrice,
                                'voucherRate' => $voucherRate,
                                'voucherMoney' => $voucherRate > 0 ? round($voucherPrice * $cell['借方数量'] / $voucherRate, 2) : 0,
                            ];
                            $mxField = [
                                'id' => suiji(),
                                'coid' => self::$coid,
                                'orderId' => $voucherInfo['id'],
                                'summary' => $cell['摘要'],
                                'subjectId' => $subject['id'],
                                'subjectName' => $subject['name'],
                                'subjectCode' => $subject['code'],
                                'direction' => $direction,
                                'money' => $money,
                                'subjectAttr' => json_encode($collection, 320),
                                'khid' => $kehu['khid'],
                                'supplierId' => $supplier['id'],
                                'staffId' => $staff['stid'],
                                'projectId' => $project['id'],
                                'departmentId' => $department['id'],
                                'materialId' => $material['id'],
                                'cashId' => $cash['id'],
                                'voucherNum' => voucherEditClass::formatNum($cell['借方数量']),
                                'currencyId' => $currency['id'],
                                'unit' => $material['unit'] ?: $subject['numAccountText'],
                                'rowList'=>$line
                            ];
                            $idCollection = array_filter([$mxField['khid'], $mxField['staffId'], $mxField['supplierId'], $mxField['projectId'], $mxField['materialId'], $mxField['departmentId'], $mxField['cashId']]);
                            asort($idCollection);
                            $mxField['idCollection'] = implode(',', $idCollection);
                            $warn = static::insert(array(
                                'table' => self::tableMx,
                                'field' => $mxField,
                            ));
                            if ($warn == '新增成功') {
                                $x++;
                                $succeed++;
                                $text .= "第【{$row_list}】行：凭证明细成功<br>";
                            } else {
                                $text .= "第【{$row_list}】行：凭证明细失败<br>";
                            }
                        }
                    }

                    $preVoucher = $cell['凭证号'];
                    if (!isset($data[$i + 1][1]) || (isset($data[$i + 1][1]) && $data[$i + 1][1] != $cell['凭证号'])) {
                        if (round($jieTotal, 2) != round($daiTotal, 2)) {
                            $text .= "凭证【{$preVoucher}】：借贷金额不相等<br>";
                            $succeed--;
                        }
                        if ($line == $succeed) {
                            $this->commitTrans();
                        } else {
                            $this->rollback();
                            $x = $x-$succeed-1;
                        }
                        $line = $succeed = 0;
                        if (isset($data[$i + 1][1])) {
                            $this->startTrans();
                        }
                    }
                }
            }

            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }


    /**
     * 样式
     */
    private function style(): string
    {
        return <<<eof
<style>
.mlf{margin-left: 20px}
.voucher-list-head,.voucher-list-line{border-bottom: 1px solid #F2F2F2}
.voucher-list-line:hover{background-color: #F2F2F2}
.voucher-list-head:hover{background-color: #F2F2F2}
.voucher-list-head{height: 40px;line-height: 40px}
.voucher-list-item{position: relative;padding: 10px 5px;border-bottom: 1px solid rgba(215, 215, 215, 1);}
.voucher-list-line{padding: 5px 0;}
.voucher-list-line>div:nth-child(3){width: 520px;text-overflow: ellipsis;white-space: nowrap;overflow: hidden}
.td-title:nth-child(3){width: 520px;text-overflow: ellipsis;white-space: nowrap;overflow: hidden}
.voucher-list-line>div{display: inline-block; vertical-align: top;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;}
.voucher-list{margin: 0 auto;overflow: auto;height: calc(100vh - 174px);}
.checked_box{width: 15px;height: 15px}
.voucher-title .td-title{float: left;}
.voucher-title{background-color: #efefef;color: #333;box-sizing: border-box;height: 34px;line-height: 34px;margin: 0 auto;width: 100%}
.out-cycle{position: absolute;left: 100px;top: 50px;width: 80px;height: 80px;border: 2px solid #2358AD;border-radius: 50%;display: grid;place-items: center;}
.inner-cycle{transform: rotate(-45deg);width: 70px;height: 70px;border: 1px solid #2358AD;border-radius: 50%;text-align: center;line-height: 70px}
.blue-sign{color:#2358AD;border-color: #2358AD}
.orange-sign{color: #F0A262;border-color: #F0A262}
.green-sign{color: #629AFD;border-color: #629AFD}
.gray-sign{color: #AAAAAA;border-color: #AAAAAA}
.red-sign{color: red;border-color: red}
.voucher-list-total{font-weight: bold;font-size: 15px;border-bottom: none}
</style>
eof;

    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, auditForm, signForm, recordForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            //获取最新结账日期
            $checkout = query('checkout', "coid = '" . self::$coid . "' order by month desc");

            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if (date('Y-m', strtotime($info['recordDate'])) <= $checkout['month']) {
                    //返回
                    $warn = "删除失败：已结账不可删除";
                } elseif ($info['workFlow'] != '待审核' && !empty($info['auditStid'])) {
                    $warn = "删除失败：已审核不可删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
                    if ($info['sourceTable']) {
                        update(array('table' => $info['sourceTable'], 'field' => ['voucherId' => ''], 'where' => "id = '$info[sourceId]'"));
                    }
                    $all = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array("table" => 'file', "where" => " id = '$val[id]' "));
                    }
                    //更新资金表里的凭证
                    update(array('table' => 'bookkeeping', 'field' => ['voucherId' => ''], 'where' => "voucherId = '$id' and coid = '" . self::$coid . "'"));
                    $voucherWord = query('voucher_word', "id = '$info[voucherWordId]'");
                    //返回
                    $warn = $voucherWord['word'] . '-' . $info['voucherNo'] . ":删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 将0转为空
     */
    public static function zeroToEmpty($money, $isEmpty = true): string
    {
        if ($isEmpty && is_numeric($money) && $money == 0) {
            return ' ';
        }
        return $money;
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'凭证号',
                    'aliasName'=>'凭证号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'摘要',
                    'aliasName'=>'摘要',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'科目编码',
                    'aliasName'=>'科目编码',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'科目名称',
                    'aliasName'=>'科目名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'外币代码',
                    'aliasName'=>'外币代码',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'借方数量',
                    'aliasName'=>'借方数量',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'借方外币',
                    'aliasName'=>'借方外币',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'借方本币',
                    'aliasName'=>'借方本币',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'贷方数量',
                    'aliasName'=>'贷方数量',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'贷方外币',
                    'aliasName'=>'贷方外币',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'贷方本币',
                    'aliasName'=>'贷方本币',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'客户编码',
                    'aliasName'=>'客户编码',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'供应商编码',
                    'aliasName'=>'供应商编码',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'供应商名称',
                    'aliasName'=>'供应商名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'员工编码',
                    'aliasName'=>'员工编码',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'员工名称',
                    'aliasName'=>'员工名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'部门编码',
                    'aliasName'=>'部门编码',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'部门名称',
                    'aliasName'=>'部门名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'项目编码',
                    'aliasName'=>'项目编码',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'项目名称',
                    'aliasName'=>'项目名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'存货编码',
                    'aliasName'=>'存货编码',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'存货名称',
                    'aliasName'=>'存货名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'现金流编码',
                    'aliasName'=>'现金流编码',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'现金流名称',
                    'aliasName'=>'现金流名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
            ]
        };
    }
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                ],
                [
                    'columnName'=>'凭证号',
                    'aliasName'=>'凭证号',
                ],
                [
                    'columnName'=>'摘要',
                    'aliasName'=>'摘要',
                ],
                [
                    'columnName'=>'科目编码',
                    'aliasName'=>'科目编码',
                ],
                [
                    'columnName'=>'科目名称',
                    'aliasName'=>'科目名称',
                ],
                [
                    'columnName'=>'外币代码',
                    'aliasName'=>'外币代码',
                ],
                [
                    'columnName'=>'借方数量',
                    'aliasName'=>'借方数量',
                ],
                [
                    'columnName'=>'借方外币',
                    'aliasName'=>'借方外币',
                ],
                [
                    'columnName'=>'借方本币',
                    'aliasName'=>'借方本币',
                ],
                [
                    'columnName'=>'贷方数量',
                    'aliasName'=>'贷方数量',
                ],
                [
                    'columnName'=>'贷方外币',
                    'aliasName'=>'贷方外币',
                ],
                [
                    'columnName'=>'贷方本币',
                    'aliasName'=>'贷方本币',
                ],
                [
                    'columnName'=>'计量单位',
                    'aliasName'=>'计量单位',
                ],
                [
                    'columnName'=>'客户编码',
                    'aliasName'=>'客户编码',
                ],
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',
                ],
                [
                    'columnName'=>'供应商编码',
                    'aliasName'=>'供应商编码',
                ],
                [
                    'columnName'=>'供应商名称',
                    'aliasName'=>'供应商名称',
                ],
                [
                    'columnName'=>'员工编码',
                    'aliasName'=>'员工编码',
                ],
                [
                    'columnName'=>'员工名称',
                    'aliasName'=>'员工名称',
                ],
                [
                    'columnName'=>'部门编码',
                    'aliasName'=>'部门编码',
                ],
                [
                    'columnName'=>'部门名称',
                    'aliasName'=>'部门名称',
                ],
                [
                    'columnName'=>'项目编码',
                    'aliasName'=>'项目编码',
                ],
                [
                    'columnName'=>'项目名称',
                    'aliasName'=>'项目名称',
                ],
                [
                    'columnName'=>'存货编码',
                    'aliasName'=>'存货编码',
                ],
                [
                    'columnName'=>'存货名称',
                    'aliasName'=>'存货名称',
                ],
                [
                    'columnName'=>'现金流编码',
                    'aliasName'=>'现金流编码',
                ],
                [
                    'columnName'=>'现金流名称',
                    'aliasName'=>'现金流名称',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
            ]
        };
    }
}
